#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("键盘事件测试：控制老虎动向");
    //调节背景板
    setAutoFillBackground(true);
    QPalette plet=this->palette();//创建调色板，platette（）是一个创建对象的函数
    plet.setColor(QPalette::Window,Qt::green);
    setPalette(plet);
    setMinimumSize(800,600);
    setMaximumSize(800,600);
    width=size().width();
    height=size().height();

    pix=new QPixmap(width,height);//设置画图板
    pix->fill(Qt::white);

    QImage originalImage("C:\\Users\\x\\Pictures\\OIP-C.jfif");//设置图像大小
    image=originalImage.scaled(120,120);

   starty=30;
   startx=30;
   step=30;

    drawpainter();

   resize(800,600);




}

Widget::~Widget()
{
    delete ui;
}

void Widget::drawpainter()
{   pix->fill(Qt::green);
    for(int i=0;i<width;i+=30)
    {QPainter p(pix);
      QPen pen(Qt::DashLine);
      p.setPen(pen);
      p.drawLine(QPoint(i,0),QPoint(i,height));
    }
    for(int i=0;i<height;i+=30)
    {QPainter p(pix);
      QPen pen(Qt::DashLine);
      p.setPen(pen);
      p.drawLine(QPoint(0,i),QPoint(width,i));
    }
     QPainter pt(pix);
     pt.drawImage(QPoint(startx,starty),image);
     update();

}

void Widget::paintEvent(QPaintEvent *event)//当部件第一次显示在屏幕上时，Qt 会自动调用 paintEvent 来绘制部件的初始外观。
{
    QPainter pt;
    pt.begin(this);
    pt.drawPixmap(QPoint(0,0),*pix);
    pt.end();
}

void Widget::keyPressEvent(QKeyEvent *ev)
{
   if(ev->key()==Qt::Key_Up)
    {
        starty=starty>0?starty-30:starty;
    }
   else if(ev->key()==Qt::Key_Down)
     {
       starty=(starty+step+image.width())<height?starty+30:starty;
   }
   else if(ev->key()==Qt::Key_Left)
   {
       startx=startx>0?startx-30:startx;
   }
   else if(ev->key()==Qt::Key_Right)
   {
        startx=(startx+step+image.width()<width)?startx+30:startx;
   }
 drawpainter();


}

